package com.appengine.news.service;

import java.io.IOException;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.appengine.news.entity.RssImageEntity;
import com.appengine.news.entity.RssItemEntity;

public class CleanService extends AbstractService{
	/**
	 * 
	 */
	private static final long serialVersionUID = -3803559052671693878L;
	private static final Logger log = Logger.getLogger(CleanService.class
			.getName());

	@Override
	protected void service(HttpServletRequest arg0, HttpServletResponse arg1)
			throws ServletException, IOException {
		final GregorianCalendar calendar = new GregorianCalendar();
		calendar.roll(Calendar.MONTH, -HOW_OLD_2_REMOVE);
		final Date time = calendar.getTime();
		deleteItems(time);
		deleteImages(time);
	}
	/**
	 * Delete items
	 * @param last2Remove
	 */
	private void deleteItems(Date last2Remove)
	{
		log.entering(CleanService.class.getName(), "deleteItems");
		final PersistenceManager pm = getPersistenceManager();

		final String msg = "Delete all rows from " + RssItemEntity.class.getName() +  " where storedData < last2Remove range 0,10";
		log.log(Level.INFO, msg);
		final Query query = pm.newQuery("select from " + RssItemEntity.class.getName() + " where storedData < last2Remove range 0,10");
		query.declareParameters("java.util.Date last2Remove");
		Object execute3 = query.execute(last2Remove);
		pm.deletePersistentAll((Collection) execute3);
		log.exiting(CleanService.class.getName(), "deleteItems");
	}
	/**
	 * Delete images
	 * @param last2Remove
	 */
	private void deleteImages(Date last2Remove)
	{
		log.entering(CleanService.class.getName(), "deleteImages");
		final PersistenceManager pm = getPersistenceManager();
		final String msg = "Delete all rows from " + RssImageEntity.class.getName() + " where modified < last2Remove range 0,10";
		log.log(Level.INFO, msg);
			
		final Query query = pm.newQuery("select from " + RssImageEntity.class.getName() + " where modified < last2Remove range 0,10");
		query.declareParameters("java.util.Date last2Remove");
		final List<RssImageEntity> items = (List<RssImageEntity>) pm.newQuery(query).execute(last2Remove);				
		pm.deletePersistentAll((Collection) items);
		log.exiting(CleanService.class.getName(), "deleteImages");
	}	
}
